package com.arvinclub.model.util;

import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 用于图片压缩
 */
class ImageSizeUtil
{

    private static byte[] compressPicForScale(byte[] imageBytes) throws Exception
    {
        if (imageBytes == null || imageBytes.length <= 0 || imageBytes.length < 300 * 1024)
            return imageBytes;
        long srcSize = imageBytes.length;
        double accuracy = getAccuracy(srcSize / 1024);
        while (imageBytes.length > 300 * 1024)
        {
            ByteArrayInputStream inputStream = new ByteArrayInputStream(imageBytes);
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(imageBytes.length);
            Thumbnails.of(inputStream).scale(accuracy).outputQuality(accuracy).toOutputStream(outputStream);
            imageBytes = outputStream.toByteArray();
        }

        return imageBytes;
    }

    private static double getAccuracy(long size)
    {
        double accuracy;
        if (size < 900)
            accuracy = 0.85;
        else if (size < 2047)
            accuracy = 0.8;
        else if (size < 3275)
            accuracy = 0.7;
        else
            accuracy = 0.4;
        return accuracy;
    }

    private static MultipartFile base64ToMultipart(String base64)
    {
        try
        {
            String[] baseStrs = base64.split(",");
            byte[] b = Base64.decodeBase64(baseStrs[1]);
            for (int i = 0; i < b.length; ++i)
                if (b[i] < 0)
                    b[i] += 256;
            return new BASE64DecodedMultipartFile(b, baseStrs[0]);
        }
        catch (Exception e)
        {
            return null;
        }
    }


    static void byte2Base64StringFun(MultipartFile[] fileImg) throws Exception
    {
        String imgData1;
        for (int i = 0; i < fileImg.length; i++)
        {
            InputStream inputStream = fileImg[i].getInputStream();
            byte[] imgData = ImageSizeUtil.compressPicForScale(getByteArray(inputStream));
            imgData1 = "data:" + fileImg[i].getContentType() + ";base64," + Base64.encodeBase64String(imgData);
            MultipartFile def = ImageSizeUtil.base64ToMultipart(imgData1);
            fileImg[i] = def;

        }
    }

    /**
     * InputStream转换为byte[]
     */
    static byte[] getByteArray(InputStream inStream) throws IOException
    {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc;
        while ((rc = inStream.read(buff, 0, 100)) > 0)
            swapStream.write(buff, 0, rc);
        return swapStream.toByteArray();
    }


}
